package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1准备日期列表数据dataList    比如近七日数据：2023-02-01、2023-02-02、2023-02-03、2023-02-04、2023-02-05、2023-02-06、2023-02-07
        List<LocalDate> dateList = getDateList(begin, end);
        //2准备营业额数据turnoverList
        //营业额 = 订单状态已完成的订单金额
        //查询orders表，查询指定时间区间内订单状态为“已完成”的订单
        //select sum(amount) from orders where status = 5 and order_time between ? and ?
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            Map<Object, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));//2023-02-01 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));//2023-02-01 23:59:59.9999999
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//营业额为null时，设置0.0
            turnoverList.add(turnover);
        });

        //3构造TurnoverReportVO对象并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1准备日期列表数据dataList    比如近七日数据：2023-02-01、2023-02-02、2023-02-03、2023-02-04、2023-02-05、2023-02-06、2023-02-07
        List<LocalDate> dateList = getDateList(begin, end);
        //2构造newUserList数据,新增用户列表
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dateList.forEach(date -> {
            //select count(*) from user where create_time >=当天开始时间 and create_time < 当天结束时间
            Map<Object, Object> map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer newUsers = userMapper.countByMap(map);
            newUserList.add(newUsers);

            //3构造totalUserList数据,总用户列表
            //select count(*) from user where create_time < 当天结束时间
            map.put("beginTime", null);
           // map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));写过了上面
            Integer totalUsers = userMapper.countByMap(map);
            totalUserList.add(totalUsers);
        });
        //4构造UserReportVO对象并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //1准备日期列表dataList
        List<LocalDate> dateList = getDateList(begin, end);
        //2获取订单列表,每日订单数orderCountList
        //统计每日订单数orders表数量条件；下单时间>= 开始时间 and 下单时间 < =结束时间
        //循环日期列表，查询每个日期对应的订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            Map<Object, Object> map = new HashMap<>();
            map.put("status", null);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer orderCount = ordersMapper.countByMap(map);
            orderCountList.add(orderCount);

            //3获取每日有效订单数validOrderCountList
            //条件；状态=已完成 下单时间>= 开始时间 and 下单时间 <=结束时间
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);

            //4获取订单总数totalOrderCount
            //select count(*) from orders where 下单时间>= 2023-02-01 00:00:00 and 下单时间 < 2023-02-07 00:00:00
            totalOrderCount += orderCount;

            //4获取有效订单数validOrderCount
            validOrderCount += validOrder;
        }
        //4获取订单总数totalOrderCount
//        Integer i = orderCountList.stream().reduce(new BinaryOperator<Integer>() {
//            @Override
//            public Integer apply(Integer integer, Integer integer2) {//累加器方法
//                return integer + integer2;
//            }
//        }).get();
//        totalOrderCount = orderCountList.stream().reduce((a, b) -> a + b).get();
//        totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();


        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = (validOrderCount+ 0.0 )/ totalOrderCount;
        }
        //6构造OrderReportVO对象并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1构造nameList商品名称列表--
        //查询订单明细表order_detail表+订单表orders，条件订单状态已完成，下单时间>=开始时间 and 下单时间<=结束时间
        List<String>nameList = new ArrayList<>();
        List numberList = new ArrayList();
        Map<Object, Object> map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        List<Map> list = ordersMapper.sumTop10(map);
        //2构造numberList商品销量-份数
        for (Map m : list) {
            nameList.add((String) m.get("name"));
            numberList.add(m.get("sumNum"));
        }

        //封装SalesTop10ReportVO
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }
/**
 * 导出数据
 * @param response
 */
    @Override
    public void export(HttpServletResponse response) throws IOException {
        //1查询数据库，获取数据  查询30天的营业额数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过poi将数据写入excel文件中
        InputStream  in = Objects.requireNonNull(this.getClass().getClassLoader().getResource("template/运营数据报表模板.xlsx")).openStream();
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取sheet1标签页
        XSSFSheet sheet1 = excel.getSheet("Sheet1");
        //填充数据 时间
        sheet1.getRow(1).getCell(1).setCellValue("时间： " + dateBegin + "至" + dateEnd);

        sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            //查询某一天的营业数据
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            sheet1.getRow(7 + i).getCell(1).setCellValue(date.toString());
            sheet1.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
            sheet1.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());
        }

        //3将excel文件输出到浏览器，进行下载
        OutputStream out = response.getOutputStream();
        excel.write(out);
        out.close();
        excel.close();

    }

    /**
     * 获取指定时间区间内的日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
